<script setup lang="ts">
import selectDialog from '../select/index.vue';
import { tableConfig } from './config/table-config';
import { formConfig } from './config/form-config';
import { formatInput, transformDataToKeys } from '@/utils';
import { doUpdateSupplier, doGetSupplierDetail } from '@/api/base/supplier/index';
import { message } from '@/components/q-message/message';
import { Plus } from '@element-plus/icons-vue';
import type { MaterialRecords, SupplierRecords } from '@/api/base/supplier/model/type';
import type { SupplerUpdateForm } from '@/views/Base/Supplier/type';

const initSupplerUpdateForm = () => {
    return {
        id: null,
        supplierCode: null,
        supplierName: null,
        supplierPerson: null,
        supplierPhone: null
    };
};

const supplerUpdateForm = ref<SupplerUpdateForm>(initSupplerUpdateForm());

const excludeKey = ref([]);
const { handleFullscreen, getMaxHeight, modalSlotRef, visible, handleCancel, loading, modalOk } =
    useModal({ appendData: supplerUpdateForm, excludeKey });

/**
 * 校验相关
 */
const { popoverVisible, popoverErrMsg, handleInput, handleFocus, handleValidFieldPass } = useValid({
    position: 'left',
    formConfig: formConfig.items,
    formFields: supplerUpdateForm,
    mountErrId: formConfig.id
});

/**
 * @: 只有等数据返回后再打开弹框并进行传递数据
 */
const materialList = ref<Partial<MaterialRecords>[]>([]);
const handleGetData = () => {
    return new Promise(resolve => {
        const res = { data: { records: materialList.value } };
        resolve(res);
    });
};

const selectRef = ref<InstanceType<typeof selectDialog>>();

/**
 * @: 选择物料
 */
const openMaterial = () => {
    selectRef.value?.open(materialList.value);
};

/**
 * @: 删除单条供应产品
 */
const handleDel = (row?: SupplierRecords, index?: number) => {
    materialList.value = materialList.value.filter(
        (item, idx) => item.materialId !== row?.materialId || idx !== index
    );
    modalSlotRef.value?.getData?.();
};

/**
 * @: 选中数据
 */
const selectMaterial = (list: MaterialRecords[]) => {
    materialList.value = [...materialList.value, ...list];
    modalSlotRef.value?.getData?.();
};

/**
 * @: 打开弹框
 */
const title = ref('编辑');
const open = async (id?: string) => {
    initData(); // 初始化数据
    try {
        if (id) {
            const { data } = await doGetSupplierDetail(id);
            if (data) {
                const { supplierCode, supplierName, supplierPerson, supplierPhone } = data;

                supplerUpdateForm.value = {
                    id,
                    supplierCode,
                    supplierName,
                    supplierPerson,
                    supplierPhone
                };
                materialList.value = data.supplierMaterials;
            }
        }
        visible.value = true;
    } catch (error) {
        console.log('error', error);
    }
};

const emit = defineEmits(['updateSuccess']);

/**
 * @: 点击确定按钮
 */
const submit = async () => {
    const formValid = handleValidFieldPass();
    const tableValid = modalSlotRef.value?.handleValidFieldPass();
    if (formValid && tableValid) {
        const dataList = materialList.value.map(item => {
            // 通过所传入的 key 获取对应参数
            return transformDataToKeys(item, [
                'supplierId',
                'materialId',
                'materialName',
                'materialCode',
                'finishedProductRate',
                'quasiDeliveryRate'
            ]);
        });
        const supplierData = {
            ...supplerUpdateForm.value,
            supplierMaterials: dataList
        };
        try {
            // 新增或编辑供应商逻辑
            const res = await doUpdateSupplier(supplierData);

            if (res) {
                message.success(`编辑供应商成功！`);
                emit('updateSuccess');
            }
            return res;
        } catch (error) {
            console.log('error', error);
        }
    }
};

/**
 * @: 初始化数据
 * @return {*}
 */
const initData = () => {
    supplerUpdateForm.value = initSupplerUpdateForm();
    materialList.value = [];
};

defineExpose({
    open
});
</script>

<template>
    <div>
        <q-modal
            v-model:visible="visible"
            :title="title"
            :fullscreen="true"
            width="1000px"
            :close-cancel="true"
            :centered="true"
            :after-close="initData"
            :confirm-loading="loading"
            @fullscreen="handleFullscreen"
            @ok="modalOk(submit)"
            @cancel="handleCancel"
        >
            <div class="p-l-8 p-r-8">
                <q-form-item :id="formConfig.id!" class="m-b-16">
                    <h2 class="m-title--common">基础信息</h2>
                </q-form-item>
                <el-row :gutter="32" class="p-l-8 p-r-8">
                    <el-col
                        v-for="item in formConfig.items"
                        :key="item.validProps?.id"
                        :span="12"
                        class="role-main__header form-common m-b-18"
                    >
                        <label class="is-column"
                            ><span>{{ item.validProps?.required ? '*' : '&nbsp;' }}</span
                            >{{ item.columnProps?.label }}:</label
                        >
                        <q-form-item :id="item.validProps?.id!" class="role-main-form__item">
                            <el-input
                                v-model.trim="supplerUpdateForm[item.modelKey!]"
                                v-bind="item.elInputProps"
                                :placeholder="`请输入${item.columnProps?.label}`"
                                :disabled="
                                    item.columnProps?.label === '供应商编码' && title === '编辑'
                                "
                                @focus="
                                    (e: any) =>
                                        handleFocus(e, supplerUpdateForm, {
                                            config: item
                                        })
                                "
                                @input="
                                    supplerUpdateForm[item.modelKey!] = formatInput(
                                        supplerUpdateForm,
                                        item.modelKey!,
                                        item.validFormatType
                                    )
                                "
                                @keyup="
                                    (e: any) =>
                                        handleInput(e, supplerUpdateForm, {
                                            config: item
                                        })
                                "
                                @blur="popoverVisible = false"
                            />
                        </q-form-item>
                    </el-col>
                </el-row>
                <base-table
                    ref="modalSlotRef"
                    class="m-t-8"
                    :max-height="getMaxHeight"
                    :modal-mode="true"
                    :show-setting="false"
                    :show-page="false"
                    :table-config="tableConfig"
                    :get-data-fn="handleGetData"
                    :close-edit="true"
                    action-width="80px"
                    @del="handleDel"
                >
                    <template #tableHeadStart>
                        <!-- 供应物料 -->
                        <h2 class="m-title--common">供应物料</h2>
                    </template>
                    <template #tableHeadEnd>
                        <el-button type="primary" :icon="Plus" @click="openMaterial">
                            选择物料
                        </el-button>
                    </template>
                    <template #finishedProductRate="{ row, item }">
                        <q-form-item :id="item.validProps!.id!">
                            <el-input-number
                                v-model="row.finishedProductRate"
                                style="width: 80%"
                                :controls="false"
                                :precision="2"
                                :max="100"
                                :min="1"
                                @focus="
                                    (e: any) =>
                                        handleFocus(e, row, {
                                            config: item
                                        })
                                "
                                @blur="popoverVisible = false"
                                @keyup="
                                    (e: any) =>
                                        handleInput(e, row, {
                                            config: item
                                        })
                                "
                            >
                            </el-input-number>
                            %
                        </q-form-item>
                    </template>
                    <template #quasiDeliveryRate="{ row, item }">
                        <q-form-item :id="item.validProps!.id!">
                            <el-input-number
                                v-model="row.quasiDeliveryRate"
                                style="width: 80%"
                                :controls="false"
                                :precision="2"
                                :min="1"
                                :max="100"
                                @focus="
                                    (e: any) =>
                                        handleFocus(e, row, {
                                            config: item
                                        })
                                "
                                @blur="popoverVisible = false"
                                @keyup="
                                    (e: any) =>
                                        handleInput(e, row, {
                                            config: item
                                        })
                                "
                            >
                            </el-input-number>
                            %
                        </q-form-item>
                    </template>
                </base-table>
            </div>
            <!-- 校验提示框 -->
            <q-valid-popover
                :popover-visible="popoverVisible"
                :popover-err-msg="popoverErrMsg"
                position="left"
            />
        </q-modal>
        <select-dialog ref="selectRef" @submit="selectMaterial" @close="visible = false" />
    </div>
</template>

<style scoped lang="scss">
@include b(role-main-form) {
    @include e(item) {
        width: 100%;
        max-width: 1000px;
    }
}

@include b(role-main__header) {
    color: var(--el-color-danger);
}

@include b(main) {
    width: 90%;
    margin: 0 auto;
}

@include b(title) {
    font-weight: 700;
}

:deep() {
    .action > span {
        margin-left: 0 !important;
    }
}
</style>
